# transform a list into a set
toSet <- function(list)
{
  return(intersect(list,list))
}

# Similarity function : Jaccard measure (mutual cover) between the set 'set1' and the set 'set2'
Jaccard <- function(set1, set2)
{
  return(length(intersect(set1, set2))/length(union(set1, set2)))
}

# Similarity function : cover of the set 'set1' on the set 'set2'
Cover <- function(set1, set2)
{
  return(length(toSet(set1))/length(union(set1, set2)))
}

#Compare the data in 'set' compared to the knowledge contain in the 'listOfSets' with the similarity function 'similarityFunc"
Compare <- function(set, listOfSets, similarityFunc)
{
  return(sapply(as.vector(listOfSets), function(x) eval(call(similarityFunc, set, x))))
}

#Relevance of the data in 'set' compared to the knowledge contain in the 'listOfSets' with the similarity function 'similarityFunc"
Relevance <- function(set, listOfSets, similarityFunc)
{
  return(max(Compare(set, listOfSets, similarityFunc), na.rm = TRUE))
}

#Loading a file into a ugly data structure for the comparison
LoadFileStats <- function(fileName, header=FALSE)
{
  return(read.table(file=fileName, sep="\t",quote = "",colClasses = "character", header=header))
}


#Loading a file into a good data structure for the comparison
LoadFileFormat <- function(fileName)
{
  l <- LoadFile(fileName)
  tmp <- sapply(l$V2, function(x) eval(call("strsplit", x, " ")))
  tmp <- as.list(tmp)
  names(tmp) <- l$V1
  return(tmp)
}

RetainsElems <- function(list, allowedElements)
{
  result <- list
  for (i in 1:length(result))
  {
    result[[i]] <- intersect(result[[i]], allowedElements)
  }
  return(result)
}

Filter <- function(list, numberLimit=2)
{
    return(list[sapply(list, function(x) eval(call("length", x)))>=numberLimit])
}

CompareAll <- function(list1, list2, similarityFunc)
{
  return(sapply(list1, function(x) eval(call("Compare", x, list2, similarityFunc))))
}

RelevanceAll <- function(list1, list2, similarityFunc)
{
  return(sapply(list1, function(x) eval(call("Relevance", x, list2, similarityFunc))))
}